package com.yikome.purchase.controller;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;

import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.web.PageableDefault;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.yikome.constant.CommonConstant;
import com.yikome.purchase.dto.PendingPurchaseProductExportDTO;
import com.yikome.purchase.entity.PendingPurchase;
import com.yikome.purchase.request.PendingPurchaseProductRequest;
import com.yikome.purchase.request.PendingPurchaseRequest;
import com.yikome.purchase.request.PurchasedPendingPurchaseRequest;
import com.yikome.purchase.service.PendingPurchaseService;
import com.google.common.base.Preconditions;
import com.itmuch.lightsecurity.annotation.PreAuthorize;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.hutool.core.util.StrUtil;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@RestController
@RequestMapping("/admin/p-purchase")
public class PendingPurchaseController {

	@Autowired
	private PendingPurchaseService pendingPurchaseService ; 
	
	@GetMapping("/combo")
	public List<Map<String , Object>> findPendingPurchaseCombo(){
		return pendingPurchaseService.findPendingPurchasePendingPurchaseCombo();
	}
	
	@GetMapping("/products")
	@PreAuthorize("hasAnyRoles('admin','purchase')")
	public Page<PendingPurchaseProductExportDTO> findPendingPurchaseProducts(PendingPurchaseProductRequest purchaseProductRequest , @PageableDefault(sort = {"supplier_id" , "product_id"}, direction = Sort.Direction.DESC)Pageable pageable){
		return pendingPurchaseService.findPendingPurchaseProduct(purchaseProductRequest, pageable);
	}
	
	@PostMapping("/create")
	@PreAuthorize("hasAnyRoles('admin','purchase')")
	public PendingPurchase createPendingPurchase(@RequestBody PendingPurchaseRequest pendingPurchaseRequest) {
		
		return pendingPurchaseService.generatePendingPurchase(pendingPurchaseRequest);
		
	}
	
	@PutMapping("/purchased")
	@PreAuthorize("hasAnyRoles('admin','purchase')")
	public List<PurchasedPendingPurchaseRequest> purchasedPendingPurchase(@RequestBody List<PurchasedPendingPurchaseRequest> purchasedPendingPurchaseRequests) {
		
		List<PurchasedPendingPurchaseRequest> errors = new ArrayList<>();
		
		for (PurchasedPendingPurchaseRequest purchasedPendingPurchaseRequest : purchasedPendingPurchaseRequests) {
			
			try {
				
				Preconditions.checkArgument(StrUtil.isNotBlank(purchasedPendingPurchaseRequest.getPendingPurchaseCode()), "参数信息不全,缺货批次不存在");
				Preconditions.checkArgument(StrUtil.isNotBlank(purchasedPendingPurchaseRequest.getProductSkuBarcode()), "参数信息不全,产品编码不存在");
				
				pendingPurchaseService.purchasedPendingPurchase(purchasedPendingPurchaseRequest.getPendingPurchaseCode(), purchasedPendingPurchaseRequest.getProductSkuBarcode());
				
			}catch (Exception e) {
				purchasedPendingPurchaseRequest.setErrorMsg(e.getMessage());
				errors.add(purchasedPendingPurchaseRequest);
			}
		}
		return errors;
	}
	
	@GetMapping("/products/export")
	@PreAuthorize("hasAnyRoles('admin','purchase')")
	public String exportPendingPurchaseProducts(PendingPurchaseProductRequest purchaseProductRequest , HttpServletResponse response) throws IOException{
		
		List<PendingPurchaseProductExportDTO> pendingPurchaseProducts = pendingPurchaseService.findPendingPurchaseProduct(purchaseProductRequest);
		
		Workbook workbook = ExcelExportUtil.exportExcel(new ExportParams(purchaseProductRequest.getPendingPurchaseCode() + "-缺货单数据", "缺货单数据"), PendingPurchaseProductExportDTO.class, pendingPurchaseProducts);
    	
    	String folderPath = CommonConstant.BASE_LOCATION + LocalDateTime.now(ZoneId.of("+8")).format(CommonConstant.DATETIMEFORMATTRT_DATE) + '/' ;
		File fileFolder = new File(folderPath);
		if (!fileFolder.exists())fileFolder.mkdirs();
		
		String fileName = LocalDateTime.now(ZoneId.of("+8")).format(CommonConstant.DATETIMEFORMATTRT_TIME) + "-缺货单数据.xlsx" ;
		
		String filePath = folderPath + fileName ;
		FileOutputStream fos = new FileOutputStream(filePath);
		workbook.write(fos);
        fos.close();
		return filePath ; 
	}
}
